package cn.edu.scau.cmi.ema.service;

import java.util.List;
import java.util.Set;

import org.springframework.stereotype.Service;

import org.springframework.transaction.annotation.Transactional;


import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Projections;
import org.hibernate.Session;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Projections;
import org.hibernate.Session;
import cn.edu.scau.cmi.ema.dao.*;
import cn.edu.scau.cmi.ema.domain.*;
import cn.edu.scau.cmi.ema.util.CmiSqlUtil;
import cn.edu.scau.cmi.ema.domain.base.CmiPagination;
import cn.edu.scau.cmi.ema.service.base.CmiEmaService;

import java.io.IOException;
import java.util.Map;
import java.util.HashMap;
import java.util.Set;
import java.util.HashSet;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import javax.persistence.Query;
import java.util.Iterator;
@Service("FoodtypeService")
@Transactional

public class FoodtypeServiceImpl extends CmiEmaService implements FoodtypeService {
	public FoodtypeServiceImpl() {
	}

	@Transactional
	public Foodtype saveFoodtype(Foodtype foodtype) {
		Set<Food> existingFoodsForFoodtype = new HashSet<Food>();
		Set<Foodtype> existingFoodtypesForParent = new HashSet<Foodtype>();
		Set<Standard> existingStandardsForStandard = new HashSet<Standard>();

		Set<Food> selectedFoodsForFoodtype = foodtype.getFoodsForFoodtype();
		Set<Foodtype> selectedFoodtypesForParent = foodtype.getFoodtypesForParent();
		Set<Standard> selectedStandardsForStandard = foodtype.getStandardsForFoodtype();

		if (foodtype.getId() == null) {
			Foodtype parent = foodtypeDAO.findFoodtypeById(foodtype.getParent().getId());

			Foodtype existingFoodtype = foodtypeDAO.findFoodtypeByPhysicalPrimaryKey(foodtype.getName(),
					parent.getId());

			foodtype.setParent(parent);

			if (isEquals(foodtype, existingFoodtype)) {
				return existingFoodtype;
			}

			foodtype = foodtypeDAO.store(foodtype);
			foodtypeDAO.flush();

			for (Food relatedFood : selectedFoodsForFoodtype) {
				relatedFood.setFoodtype(foodtype);
				foodDAO.store(relatedFood);
			}
			for (Foodtype relatedFoodtype : selectedFoodtypesForParent) {
				relatedFoodtype.setParent(foodtype);
				foodtypeDAO.store(relatedFoodtype);
			}

			for (Standard relatedStandard : selectedStandardsForStandard) {
				relatedStandard.getFoodtypesForStandard().add(foodtype);
				standardDAO.store(relatedStandard);
			}
		} else {
			Foodtype existingFoodtype = foodtypeDAO.findFoodtypeByPrimaryKey(foodtype.getId());

			existingFoodsForFoodtype = existingFoodtype.getFoodsForFoodtype();
			existingFoodtypesForParent = existingFoodtype.getFoodtypesForParent();
			existingStandardsForStandard = existingFoodtype.getStandardsForFoodtype();

			Set<Food> prepareDeleteFoodsForFoodtype = new HashSet<Food>();
			Set<Food> prepareAddFoodsForFoodtype = new HashSet<Food>();

			prepareDeleteFoodsForFoodtype.addAll(selectedFoodsForFoodtype);
			prepareDeleteFoodsForFoodtype.addAll(existingFoodsForFoodtype);

			prepareAddFoodsForFoodtype.addAll(selectedFoodsForFoodtype);
			prepareAddFoodsForFoodtype.addAll(existingFoodsForFoodtype);

			prepareDeleteFoodsForFoodtype.removeAll(selectedFoodsForFoodtype);
			prepareAddFoodsForFoodtype.removeAll(existingFoodsForFoodtype);

			for (Food relatedFood : prepareAddFoodsForFoodtype) {
				relatedFood.setFoodtype(foodtype);
				foodDAO.store(relatedFood);
			}

			for (Food relatedFood : prepareDeleteFoodsForFoodtype) {
				relatedFood.setFoodtype(null);
				foodDAO.store(relatedFood);
			}
			Set<Foodtype> prepareDeleteFoodtypesForParent = new HashSet<Foodtype>();
			Set<Foodtype> prepareAddFoodtypesForParent = new HashSet<Foodtype>();

			prepareDeleteFoodtypesForParent.addAll(selectedFoodtypesForParent);
			prepareDeleteFoodtypesForParent.addAll(existingFoodtypesForParent);

			prepareAddFoodtypesForParent.addAll(selectedFoodtypesForParent);
			prepareAddFoodtypesForParent.addAll(existingFoodtypesForParent);

			prepareDeleteFoodtypesForParent.removeAll(selectedFoodtypesForParent);
			prepareAddFoodtypesForParent.removeAll(existingFoodtypesForParent);

			for (Foodtype relatedFoodtype : prepareAddFoodtypesForParent) {
				relatedFoodtype.setParent(foodtype);
				foodtypeDAO.store(relatedFoodtype);
			}

			for (Foodtype relatedFoodtype : prepareDeleteFoodtypesForParent) {
				relatedFoodtype.setParent(null);
				foodtypeDAO.store(relatedFoodtype);
			}
			Set<Standard> prepareDeleteStandardsForStandard = new HashSet<Standard>();
			Set<Standard> prepareAddStandardsForStandard = new HashSet<Standard>();

			prepareDeleteStandardsForStandard.addAll(selectedStandardsForStandard);
			prepareDeleteStandardsForStandard.addAll(existingStandardsForStandard);

			prepareAddStandardsForStandard.addAll(selectedStandardsForStandard);
			prepareAddStandardsForStandard.addAll(existingStandardsForStandard);

			prepareDeleteStandardsForStandard.removeAll(selectedStandardsForStandard);
			prepareAddStandardsForStandard.removeAll(existingStandardsForStandard);

			for (Standard relatedStandard : prepareAddStandardsForStandard) {

				relatedStandard.getFoodtypesForStandard().add(existingFoodtype);
				standardDAO.store(relatedStandard);
			}

			for (Standard relatedStandard : prepareDeleteStandardsForStandard) {

				relatedStandard.getFoodtypesForStandard().remove(existingFoodtype);
				standardDAO.store(relatedStandard);
			}
			foodtype = foodtypeDAO.store(foodtype);
			foodtypeDAO.flush();
		}

		foodDAO.flush();
		foodtypeDAO.flush();
		standardDAO.flush();
		return foodtype;
	}

	public void deleteFoodtype(Foodtype foodtype) {
		foodtypeDAO.remove(foodtype);
		foodtypeDAO.flush();
	}

	@Transactional
	public void deleteFoodtypes(Set<Integer> deleteFoodtypesId) {
		Query query = foodtypeDAO.createNamedQuery("deleteFoodtypesById", -1, -1);
		query.setParameter(1, deleteFoodtypesId);
		query.executeUpdate();
	}

	@Transactional
	public Set<Foodtype> loadFoodtypes() {
		return foodtypeDAO.findAllFoodtypes();

	}

	@Transactional
	public Set<Foodtype> loadReferenceFoodtypes(Set<Foodtype> foodtypes) {
		Iterator<Foodtype> foodtypesIterator = foodtypes.iterator();
		Set<Foodtype> referencedFoodtypes = new HashSet<>();
		while (foodtypesIterator.hasNext()) {
			Foodtype currentFoodtype = foodtypesIterator.next();

			if (!currentFoodtype.getFoodsForFoodtype().isEmpty()) {
				referencedFoodtypes.add(currentFoodtype);
				continue;
			}

			if (!currentFoodtype.getFoodtypesForParent().isEmpty()) {
				referencedFoodtypes.add(currentFoodtype);
				continue;
			}

			if (!currentFoodtype.getStandardsForFoodtype().isEmpty()) {
				referencedFoodtypes.add(currentFoodtype);
				continue;
			}
		}
		return referencedFoodtypes;
	}

	public Set<Foodtype> loadFoodtypesByIdSet(Set<Integer> foodtypeIdSet) {

		Iterator<Integer> foodtypeIdIterator = foodtypeIdSet.iterator();
		Set<Foodtype> foodtypeSet = new HashSet<>();
		while (foodtypeIdIterator.hasNext()) {
			Integer id = foodtypeIdIterator.next();
			Foodtype currentFoodtype = foodtypeDAO.findFoodtypeById(id);
			foodtypeSet.add(currentFoodtype);
		}
		return foodtypeSet;
	}

	@Transactional
	public List<Foodtype> findAllFoodtypes(Integer startResult, Integer maxRows) {
		return new java.util.ArrayList<Foodtype>(foodtypeDAO.findAllFoodtypes(startResult, maxRows));
	}

	@Transactional
	public Foodtype findFoodtypeByPrimaryKey(Integer id) {
		return foodtypeDAO.findFoodtypeByPrimaryKey(id);
	}

	@Transactional
	public Integer countFoodtypes() {
		return ((Long) foodtypeDAO.createQuerySingleResult("select count(o) from Foodtype o").getSingleResult())
				.intValue();
	}

	@Transactional
	public Integer countFoodtypes(CmiPagination page) {
		String sql = CmiSqlUtil.createCountHql(page, Foodtype.class);
		return ((Long) foodtypeDAO.createQuerySingleResult(sql).getSingleResult()).intValue();
	}

	/**
	 * search for name with ajax
	 * 
	 */
	@Transactional
	public Integer countFoodtypesByName(String queryName) {
		Query query = foodtypeDAO.createNamedQuery("countFoodtypesByName", -1, -1);
		query.setParameter(1, queryName);
		return new Long((long) query.getSingleResult()).intValue();
	}

	@Transactional
	public Integer countFoodtypesByDetachedCriteria(CmiPagination page) {
		DetachedCriteria detachedCriteria = CmiSqlUtil.createDetachedCriteria(page, Foodtype.class);
		Session session = entityManager.unwrap(Session.class);
		detachedCriteria.setProjection(Projections.rowCount());
		return new Long((long) detachedCriteria.getExecutableCriteria(session).uniqueResult()).intValue();
	}

	public Map<String, ?> loadFoodtypeObjectReferencedSet(Foodtype foodtype) {
		HashMap<String, Object> objectReferencedSetMap = new HashMap<>();
		if (foodtype.getParent() != null) {

			Set<Integer> parentIds = new HashSet<Integer>();
			parentIds.add(foodtype.getParent().getId());
			objectReferencedSetMap.put("parentIds", parentIds);
		}

		Set<Integer> foodsIds = new HashSet<Integer>();
		for (Food obj : foodtype.getFoodsForFoodtype()) {

			foodsIds.add(obj.getId());
		}
		objectReferencedSetMap.put("foodsIds", foodsIds);
		Set<Integer> foodtypesIds = new HashSet<Integer>();
		for (Foodtype obj : foodtype.getFoodtypesForParent()) {

			foodtypesIds.add(obj.getId());
		}
		objectReferencedSetMap.put("foodtypesIds", foodtypesIds);
		Set<Integer> standardsIds = new HashSet<Integer>();
		for (Standard standard : foodtype.getStandardsForFoodtype()) {
			standardsIds.add(standard.getId());
		}
		objectReferencedSetMap.put("standardsIds", standardsIds);

		return objectReferencedSetMap;
	}

	public Map<String, ?> loadFoodtypeClassReferencedSet(Foodtype foodtype) {
		HashMap<String, Object> classReferencedSetMap = new HashMap<>();
		classReferencedSetMap.put("foods", foodDAO.findAllFoods());
		classReferencedSetMap.put("foodtypes", foodtypeDAO.findAllFoodtypes());
		classReferencedSetMap.put("standards", standardDAO.findAllStandards());

		return classReferencedSetMap;
	}

	public boolean isEquals(Foodtype foodtype, Object obj) {
		if (obj == foodtype)
			return true;
		if (!(obj instanceof Foodtype))
			return false;
		Foodtype comparedFoodtype = (Foodtype) obj;
		if (!CheckPropertyEqual(foodtype.getName(), comparedFoodtype.getName())) {
			return false;
		}
		if (!CheckPropertyEqual(foodtype.getParent().getId(), comparedFoodtype.getParent().getId())) {
			return false;
		}
		return true;
	}

	public static <T> boolean CheckPropertyEqual(T originProperty, T comparedProperty) {
		// 基本类型经过参数传递后会自动装箱
		String[] className = originProperty.getClass().getName().split("\\.");
		if (className[0].equals("java") && className[1].equals("math")) {
			return ((Comparable) originProperty).compareTo(comparedProperty) == 0 ? true : false;
		} else {
			return originProperty.equals(comparedProperty);
		}
	}
}

